package lsp;

import java.util.concurrent.atomic.AtomicBoolean;

import api.LspParams;

public class EpochTrigger implements Runnable {
	private LspParams params;
	private AtomicBoolean epochExpired;
	private AtomicBoolean epochLimitExpired;
	private int epochExpiredCount = 0;

	public EpochTrigger(LspParams params, AtomicBoolean epochExpired,
			AtomicBoolean epochLimitExpired) {
		this.params = params;
		this.epochExpired = epochExpired;
		this.epochLimitExpired = epochLimitExpired;
	}

	@Override
	public void run() {
		while (true) {
			if (epochExpired.get()) {
				System.err.println("Conexoa perdida.");
				break;
			}
			try {
				Thread.sleep(this.params.getEpoch() * 1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			if (epochExpired.get())
				epochExpiredCount = epochExpiredCount + 1;
			else
				epochExpiredCount = 0;
			if (epochExpiredCount == params.getEpochLimit()) {
				epochLimitExpired.set(true);
				continue;
			}
			epochExpired.set(true);
		}
	}

}
